package com.sunricher.dancing_with_flutter.demo;

import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.HashMap;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "samples.flutter.dev/battery";

    // 使用 extends FlutterActivity 并且没有 setViewContent 才能走此方法，
    // 否则此方法不会被调用。
    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        Log.d("MainActivity", "configureFlutterEngine");
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler((call, result) -> {
            // This method is invoked on the main thread.
            if (call.method.equals("getBatteryLevel")) {
                int batteryLevel = getBatteryLevel();
                if (batteryLevel != -1) {
                    result.success(batteryLevel);
                } else {
                    result.error("UNAVAILABLE", "Battery level not available.", null);
                }
            } else {
                result.notImplemented();
            }
            Log.d("MainActivity", "methodCallHandler " + call.method);


        });
    }

    private int getBatteryLevel() {
        int batteryLevel = -1;
        BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
        batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

        return batteryLevel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // EdgeToEdge.enable(this);
        Log.d("MainActivity", "onCreate");

        // 如果使 App 一开始就打开 FlutterActivity: public class MainActivity extends FlutterActivity
        // 则需要注释下面所有的代码，不要 setContentView

        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 如果没有使用缓存的 FlutterEngine 则需要在此初始化
        /*
        // 1. 初始化 FlutterEngine
        flutterEngine = new FlutterEngine(this);
        flutterEngine.getDartExecutor().executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        );

        // 2. 缓存引擎（如果需要）
        FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine);
         */

        FlutterEngine flutterEngine = FlutterEngineCache.getInstance().get("my_engine_id");
        if (flutterEngine != null) {
            MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
            methodChannel.setMethodCallHandler((call, result) -> {
                // This method is invoked on the main thread.
                if (call.method.equals("getBatteryLevel")) {
                    int batteryLevel = getBatteryLevel();
                    if (batteryLevel != -1) {
                        result.success(batteryLevel);
                    } else {
                        result.error("UNAVAILABLE", "Battery level not available.", null);
                    }
                } else {
                    result.notImplemented();
                }
                Log.d("MainActivity", "methodCallHandler " + call.method);
                HashMap<String, Object> data = new HashMap<>();
                data.put("name", "Android");
                data.put("age", 18);
                new Handler().postDelayed(() -> {
                    sendDataToFlutter(methodChannel, data);
                }, 2000);
            });
        }

        findViewById(R.id.btn).setOnClickListener((v) -> {
            // do not use a flutter engine
            // startActivity(FlutterActivity.createDefaultIntent(MainActivity.this));

            // use a flutter engine
            startActivity(FlutterActivity.withCachedEngine("my_engine_id").build(MainActivity.this));
        });
    }

    private void sendDataToFlutter(MethodChannel channel, HashMap<String, Object> data) {
        channel.invokeMethod("sendDataToFlutter", data, new MethodChannel.Result() {
            @Override
            public void success(@Nullable Object result) {
                Log.d("MainActivity", "result success");
            }

            @Override
            public void error(@NonNull String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
                Log.d("MainActivity", "result error");
            }

            @Override
            public void notImplemented() {
                Log.d("MainActivity", "result notImplemented");
            }
        });
    }
}